package org.lql.algo.codecrush.hot100.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author: liangqinglong
 * @date: 2025-08-30 21:54
 * @description: 56. 合并区间 <a href="https://leetcode.cn/problems/merge-intervals/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class Merge {

	public int[][] merge(int[][] intervals) {
		Arrays.sort(intervals, Comparator.<int[]>comparingInt(a -> a[0]).thenComparingInt(a -> a[1]));
		List<int[]> ans = new ArrayList<>();
		int start = -1;
		int farthest = -1;
		for (int[] interval : intervals) {
			int left = interval[0];
			int right = interval[1];
			if (left <= farthest) {
				farthest = Math.max(farthest, right);
			} else {
				if (farthest != -1) {
					ans.add(new int[]{start, farthest});
				}
				start = left;
				farthest = right;
			}
		}
		ans.add(new int[]{start, farthest});
		return ans.toArray(new int[ans.size()][]);
	}

	public static void main(String[] args) {
		Merge merge = new Merge();
		// [[1,6],[8,10],[15,18]]
		System.out.println(Arrays.deepToString(merge.merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}})));
		// [[1,5]]
		System.out.println(Arrays.deepToString(merge.merge(new int[][]{{1, 4}, {4, 5}})));
		// [[0,4]]
		System.out.println(Arrays.deepToString(merge.merge(new int[][]{{1, 4}, {0, 4}})));
	}
}
